<script setup lang="ts">
import { ref, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { UploadProps, UploadUserFile } from 'element-plus'

const emit = defineEmits(["fileUploaded"])

const fileList = ref<UploadUserFile[]>([
])

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `一次只能上传一个文件，您选择了 ${files.length} 个文件 ${
      files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `取消上传文件： ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

const handleSuccess: UploadProps['onSuccess'] = (response: any, uploadFile, uploadFiles) => {
  emit('fileUploaded', response)
}


const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  fileList.value = []
  return true
}

</script>

<template>
    <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      action="/api/upload"
      multiple
      :on-preview="handlePreview"
      accept=".pdf"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="1"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :before-upload="handleBeforeUpload"
  >
    <el-button type="primary">点击上传PDF文件</el-button>
    <template #tip>
      <div class="el-upload__tip">
        仅支持PDF格式的文件
      </div>
    </template>
  </el-upload>
</template>
